package br.ufpe.cin.analysis.plugin.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import br.ufpe.cin.analysis.plugin.entities.Activity;
import br.ufpe.cin.analysis.plugin.entities.Lane;

public class XPDLReader implements IXpdl{


	private Scanner input;

	public XPDLReader(File xmlFile) throws FileNotFoundException
	{
		this.input = new Scanner(xmlFile);

	}

	public Vector<Lane> getLanes() {

		return new Vector<Lane>(this.analyseText());
	}

	private String loadText()
	{
		String text = new String();

		while(true)
		{
			try{
				text += this.input.next();


			}catch(Exception e)
			{
				break;				
			}
		}


		return text;
	}

	private Collection<Lane> analyseText()
	{
		String text = this.loadText();

		String RE_LaneTag = "<xpdl:Lane[\\w\\s=(\")]*>";
		String RE_ActivityTag = "<xpdl:Activity[\\w\\s(\")=<>/:]*</xpdl:Performer>";
		String RE_PerformerTag = "<xpdl:Performer>[\\w\\s]*</xpdl:Performer>";
		String RE_NameId = "\"[\\w\\s]*\"";


		Pattern pLane = Pattern.compile(RE_LaneTag);
		Pattern pActivity = Pattern.compile(RE_ActivityTag);
		Pattern pPerformer = Pattern.compile(RE_PerformerTag);
		Pattern pNameId = Pattern.compile(RE_NameId);

		Matcher laneMatcher = pLane.matcher(text);
		Matcher activityMatcher = pActivity.matcher(text);

		Matcher nameIdMatcher = null;

		Matcher performerMatcher = null;

		HashMap<String, Lane> hash = new HashMap<String, Lane>();
		Lane laneTemp = new Lane("");
		
		String str = null;

		while( laneMatcher.find() )
		{			
			nameIdMatcher = pNameId.matcher(laneMatcher.group());

			if( nameIdMatcher.find() && nameIdMatcher.find() ) {
				str = nameIdMatcher.group();
				laneTemp = new Lane(str.substring(1, str.length() - 1));
			}

			hash.put(laneTemp.getName(), laneTemp);


		}
		
		Activity acTemp = new Activity("");

		while( activityMatcher.find() )
		{
			nameIdMatcher = pNameId.matcher(activityMatcher.group());
			
			if( nameIdMatcher.find() && nameIdMatcher.find() ){
				str = nameIdMatcher.group();
				acTemp = new Activity(str.substring(1, str.length() - 1));
			}
		
			performerMatcher = pPerformer.matcher(activityMatcher.group());
			
			if( performerMatcher.find() ){
				
				str = performerMatcher.group();
				str = str.substring(str.indexOf('>') + 1, str.substring(1).indexOf('<') + 1);
				hash.get(str).getActivities().add(acTemp);
			}
		}
		
		return hash.values();
	}

}
